<template>
  <div class="addresses-container">
    <div class="addresses-header">
      <h2>收货地址</h2>
      <button class="add-address-button" @click="showAddModal">
        添加新地址
      </button>
    </div>
    
    <!-- 地址列表 -->
    <div class="addresses-list">
      <div v-if="isLoading" class="loading-state">加载中...</div>
      
      <div v-else-if="userStore.addresses.length === 0" class="empty-state">
        <div class="empty-icon">🏠</div>
        <p>暂无收货地址</p>
        <button class="add-first-address-button" @click="showAddModal">
          添加收货地址
        </button>
      </div>
      
      <div v-else class="address-grid">
        <div v-for="address in userStore.addresses" :key="address.id" class="address-item">
          <div class="address-content">
            <!-- 默认地址标签 -->
            <div v-if="address.isDefault" class="default-tag">默认</div>
            
            <!-- 收件人信息 -->
            <div class="recipient-info">
              <span class="recipient-name">{{ address.name }}</span>
              <span class="recipient-phone">{{ address.phone }}</span>
            </div>
            
            <!-- 地址信息 -->
            <div class="address-detail">
              {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
            </div>
            
            <!-- 操作按钮 -->
            <div class="address-actions">
              <button
                v-if="!address.isDefault"
                class="action-button set-default-button"
                @click="setDefaultAddress(address.id)"
              >
                设为默认
              </button>
              <button
                class="action-button edit-button"
                @click="editAddress(address)"
              >
                编辑
              </button>
              <button
                class="action-button delete-button"
                @click="deleteAddress(address.id)"
              >
                删除
              </button>
            </div>
          </div>
        </div>
        
        <!-- 添加地址卡片 -->
        <div class="address-item add-address-item" @click="showAddModal">
          <div class="add-address-content">
            <div class="add-icon">+</div>
            <p>添加新地址</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑地址模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑地址' : '添加新地址' }}</h3>
          <button class="close-button" @click="closeModal">&times;</button>
        </div>
        
        <form class="address-form" @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="name">收货人</label>
            <input
              type="text"
              id="name"
              v-model="addressForm.name"
              placeholder="请输入收货人姓名"
              required
              class="form-input"
              :class="{ 'input-error': errors.name }"
            />
            <div v-if="errors.name" class="error-text">{{ errors.name }}</div>
          </div>
          
          <div class="form-group">
            <label for="phone">手机号码</label>
            <input
              type="tel"
              id="phone"
              v-model="addressForm.phone"
              placeholder="请输入手机号码"
              required
              class="form-input"
              :class="{ 'input-error': errors.phone }"
            />
            <div v-if="errors.phone" class="error-text">{{ errors.phone }}</div>
          </div>
          
          <div class="form-group">
            <label>所在地区</label>
            <div class="region-selectors">
              <select v-model="addressForm.province" required class="region-select">
                <option value="">请选择省份</option>
                <option value="北京市">北京市</option>
                <option value="上海市">上海市</option>
                <option value="广东省">广东省</option>
                <option value="江苏省">江苏省</option>
                <option value="浙江省">浙江省</option>
                <!-- 更多省份选项 -->
              </select>
              <select v-model="addressForm.city" required class="region-select">
                <option value="">请选择城市</option>
                <option value="北京市">北京市</option>
                <option value="上海市">上海市</option>
                <option value="广州市">广州市</option>
                <option value="深圳市">深圳市</option>
                <option value="杭州市">杭州市</option>
                <option value="南京市">南京市</option>
                <!-- 更多城市选项 -->
              </select>
              <select v-model="addressForm.district" required class="region-select">
                <option value="">请选择区/县</option>
                <option value="朝阳区">朝阳区</option>
                <option value="海淀区">海淀区</option>
                <option value="浦东新区">浦东新区</option>
                <option value="天河区">天河区</option>
                <option value="福田区">福田区</option>
                <!-- 更多区县选项 -->
              </select>
            </div>
          </div>
          
          <div class="form-group">
            <label for="detail">详细地址</label>
            <textarea
              id="detail"
              v-model="addressForm.detail"
              placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等"
              required
              rows="3"
              class="form-textarea"
              :class="{ 'input-error': errors.detail }"
            ></textarea>
            <div v-if="errors.detail" class="error-text">{{ errors.detail }}</div>
          </div>
          
          <div class="form-group">
            <label class="checkbox-label">
              <input
                type="checkbox"
                v-model="addressForm.isDefault"
              />
              <span>设为默认收货地址</span>
            </label>
          </div>
          
          <div class="form-actions">
            <button type="button" class="cancel-button" @click="closeModal">取消</button>
            <button type="submit" class="submit-button" :disabled="isSubmitting">
              {{ isSubmitting ? '保存中...' : '保存' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()

const isLoading = ref(false)
const showModal = ref(false)
const isEditing = ref(false)
const editingAddressId = ref(null)
const isSubmitting = ref(false)
const errors = reactive({})

// 初始化地址表单
const addressForm = reactive({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
})

// 加载地址列表
const loadAddresses = async () => {
  isLoading.value = true
  try {
    await userStore.fetchAddresses()
  } catch (error) {
    console.error('加载地址失败:', error)
    alert('加载地址失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 显示添加地址模态框
const showAddModal = () => {
  resetForm()
  isEditing.value = false
  editingAddressId.value = null
  showModal.value = true
}

// 编辑地址
const editAddress = (address) => {
  resetForm()
  isEditing.value = true
  editingAddressId.value = address.id
  
  // 填充表单数据
  addressForm.name = address.name
  addressForm.phone = address.phone
  addressForm.province = address.province
  addressForm.city = address.city
  addressForm.district = address.district
  addressForm.detail = address.detail
  addressForm.isDefault = address.isDefault
  
  showModal.value = true
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.keys(addressForm).forEach(key => {
    addressForm[key] = ''
  })
  addressForm.isDefault = false
  
  // 清空错误信息
  Object.keys(errors).forEach(key => {
    delete errors[key]
  })
}

// 验证表单
const validateForm = () => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    delete errors[key]
  })
  
  // 验证收货人姓名
  if (!addressForm.name.trim()) {
    errors.name = '请输入收货人姓名'
    isValid = false
  }
  
  // 验证手机号码
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!addressForm.phone.trim()) {
    errors.phone = '请输入手机号码'
    isValid = false
  } else if (!phoneRegex.test(addressForm.phone.trim())) {
    errors.phone = '请输入有效的手机号码'
    isValid = false
  }
  
  // 验证所在地区
  if (!addressForm.province) {
    errors.region = '请选择省份'
    isValid = false
  }
  if (!addressForm.city) {
    errors.region = '请选择城市'
    isValid = false
  }
  if (!addressForm.district) {
    errors.region = '请选择区/县'
    isValid = false
  }
  
  // 验证详细地址
  if (!addressForm.detail.trim()) {
    errors.detail = '请输入详细地址'
    isValid = false
  } else if (addressForm.detail.trim().length < 5) {
    errors.detail = '详细地址至少需要5个字符'
    isValid = false
  }
  
  return isValid
}

// 提交表单
const handleSubmit = async () => {
  // 验证表单
  if (!validateForm()) {
    return
  }
  
  isSubmitting.value = true
  
  try {
    const addressData = {
      name: addressForm.name.trim(),
      phone: addressForm.phone.trim(),
      province: addressForm.province,
      city: addressForm.city,
      district: addressForm.district,
      detail: addressForm.detail.trim(),
      isDefault: addressForm.isDefault
    }
    
    if (isEditing.value && editingAddressId.value) {
      // 更新地址
      await userStore.updateAddress(editingAddressId.value, addressData)
    } else {
      // 添加新地址
      await userStore.addAddress(addressData)
    }
    
    // 如果设置为默认地址，更新其他地址
    if (addressForm.isDefault) {
      await userStore.setDefaultAddress(isEditing.value ? editingAddressId.value : userStore.addresses[userStore.addresses.length - 1].id)
    }
    
    // 关闭模态框
    closeModal()
    
    // 刷新地址列表
    await loadAddresses()
    
    // 显示成功提示
    alert(isEditing.value ? '地址更新成功！' : '地址添加成功！')
  } catch (error) {
    console.error('保存地址失败:', error)
    alert('保存地址失败，请稍后重试')
  } finally {
    isSubmitting.value = false
  }
}

// 设置默认地址
const setDefaultAddress = async (addressId) => {
  try {
    await userStore.setDefaultAddress(addressId)
    alert('默认地址设置成功！')
  } catch (error) {
    console.error('设置默认地址失败:', error)
    alert('设置默认地址失败，请稍后重试')
  }
}

// 删除地址
const deleteAddress = async (addressId) => {
  // 检查是否为默认地址
  const address = userStore.addresses.find(addr => addr.id === addressId)
  if (address && address.isDefault) {
    alert('默认地址不能直接删除，请先将其他地址设为默认地址')
    return
  }
  
  if (confirm('确定要删除该收货地址吗？')) {
    try {
      await userStore.deleteAddress(addressId)
      alert('地址删除成功！')
    } catch (error) {
      console.error('删除地址失败:', error)
      alert('删除地址失败，请稍后重试')
    }
  }
}

// 组件挂载时加载地址列表
onMounted(() => {
  loadAddresses()
})
</script>

<style scoped>
.addresses-container {
  padding: 32px;
}

.addresses-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.addresses-header h2 {
  margin: 0;
  font-size: 22px;
  color: #333;
}

.add-address-button {
  padding: 8px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-address-button:hover {
  background-color: #3367d6;
}

/* 地址列表 */
.addresses-list {
  margin-bottom: 24px;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.add-first-address-button {
  padding: 10px 24px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-first-address-button:hover {
  background-color: #3367d6;
}

/* 地址网格 */
.address-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.address-item {
  border: 1px solid #eee;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.address-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.address-content {
  padding: 20px;
  position: relative;
}

.default-tag {
  position: absolute;
  top: 20px;
  left: 0;
  background-color: #4285f4;
  color: white;
  padding: 2px 12px;
  font-size: 12px;
  border-radius: 0 12px 12px 0;
}

.recipient-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.recipient-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.recipient-phone {
  font-size: 14px;
  color: #666;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16px;
  word-break: break-word;
}

.address-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-button {
  padding: 4px 12px;
  border: 1px solid #ddd;
  background-color: white;
  color: #666;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-button:hover {
  border-color: #4285f4;
  color: #4285f4;
}

.set-default-button {
  border-color: #4285f4;
  color: #4285f4;
}

.set-default-button:hover {
  background-color: #e8f0fe;
}

.delete-button {
  border-color: #d32f2f;
  color: #d32f2f;
}

.delete-button:hover {
  background-color: #fee;
}

/* 添加地址卡片 */
.add-address-item {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #ddd;
  background-color: #fafafa;
  min-height: 180px;
  cursor: pointer;
}

.add-address-item:hover {
  border-color: #4285f4;
  background-color: #f8f9fa;
  transform: none;
  box-shadow: none;
}

.add-address-content {
  text-align: center;
  color: #999;
}

.add-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.add-address-content p {
  margin: 0;
  font-size: 14px;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-button:hover {
  background-color: #f5f5f5;
  color: #333;
}

/* 表单样式 */
.address-form {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-input,
.form-textarea,
.region-select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus,
.region-select:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}

.input-error {
  border-color: #d32f2f !important;
}

.error-text {
  color: #d32f2f;
  font-size: 12px;
  margin-top: 4px;
}

.region-selectors {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  width: auto;
  margin: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
}

.cancel-button {
  padding: 10px 24px;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.cancel-button:hover {
  background-color: #e0e0e0;
}

.submit-button {
  padding: 10px 24px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-button:hover:not(:disabled) {
  background-color: #3367d6;
}

.submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .addresses-container {
    padding: 20px;
  }
  
  .addresses-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .address-grid {
    grid-template-columns: 1fr;
  }
  
  .modal-content {
    margin: 20px;
    width: calc(100% - 40px);
  }
  
  .region-selectors {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions button {
    width: 100%;
  }
}
</style>